<template>
  <div class="DatabasequestionAddBody">
    <!-- 抽屉 -->
    <el-drawer
      :close-on-click-modal="false"
      v-model="drawer"
      :before-close="handleClose"
      :title="params.id ? '试题修改' : '试题添加'"
      :with-header="true"
    >
      <div class="body">
        <!-- 题的类型 -->
        <el-radio-group
          v-model="params.type"
          class="ml-4"
          style="margin-left: 20px; margin-bottom: 10px"
          @change="radioChange"
        >
          <el-radio label="单选题" size="large">单选题</el-radio>
          <el-radio label="多选题" size="large">多选题</el-radio>
          <el-radio label="判断题" size="large">判断题</el-radio>
          <el-radio label="填空题" size="large">填空题</el-radio>
          <el-radio label="问答题" size="large">问答题</el-radio>
        </el-radio-group>
        <!-- 表单 -->
        <el-form
          ref="ruleFormRef"
          :model="params"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
        >
          <el-form-item label="题干" prop="title">
            <!-- 富文本编辑器 -->
            <div style="border: 1px solid #ccc; width: 100%">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="
                  height: 150px;
                  overflow-y: hidden;
                  word-wrap: break-word;
                  word-break: normal;
                "
                v-model="params.title"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
          <!-- 选项 -->
          <el-form-item
            label="选项"
            prop="answers"
            v-show="params.type === '单选题' || params.type === '多选题'"
          >
            <div style="border-top: #fff 1px solid">
              <div
                v-for="(item, index) in params.answers"
                :key="index"
                style="display: flex; height: auto; margin: 5px 0 20px"
              >
                <span>{{ item.answerno }}：</span>
                <div>
                  <el-input
                    v-model="item.content"
                    style="width: 200px"
                    :rows="1"
                    type="textarea"
                  />
                </div>
                <el-icon
                  @click="answersDel(index)"
                  style="
                    color: red;
                    font-size: 20px;
                    margin-left: 10px;
                    margin-top: 8px;
                  "
                  ><CircleClose
                /></el-icon>
              </div>
              <el-icon
                @click="answersAdd"
                style="color: #59a0ff; font-size: 30px; margin-left: 20px"
                ><CirclePlus
              /></el-icon>
            </div>
          </el-form-item>
          <!-- 正确答案 -->
          <el-form-item
            label="正确答案"
            v-if="
              params.type === '单选题' ||
              params.type === '多选题' ||
              params.type === '判断题' ||
              blank.length > 0
            "
          >
            <!-- 填空题 -->
            <div style="width: 200px" v-if="params.type === '填空题'">
              <el-input
                v-model="blank[index]"
                style="margin-bottom: 10px"
                v-for="(item, index) in blank"
                :key="index"
              />
            </div>

            <!-- 单选 -->
            <el-radio-group
              v-model="params.answer"
              class="ml-4"
              v-if="params.type === '单选题'"
            >
              <el-radio
                v-for="(item, index) in params.answers"
                :key="index"
                :label="item.answerno"
                size="large"
                >{{ item.answerno }}</el-radio
              >
            </el-radio-group>
            <!-- 多选 -->
            <el-checkbox-group
              v-if="params.type === '多选题'"
              v-model="checked"
              @change="checkboxChange"
            >
              <el-checkbox
                v-for="(item, index) in params.answers"
                :key="index"
                :label="item.answerno"
              />
            </el-checkbox-group>
            <!-- 判断题 -->
            <el-radio-group
              v-model="params.answer"
              v-show="params.type === '判断题'"
            >
              <el-radio-button label="正确" />
              <el-radio-button label="错误" />
            </el-radio-group>
          </el-form-item>
          <!-- 解析 -->
          <el-form-item
            label="解析"
            prop="explains"
            v-show="params.type === '填空题' || params.type === '问答题'"
          >
            <el-input
              v-model="params.explains"
              style="width: 300px"
              :rows="4"
              type="textarea"
            />
          </el-form-item>
          <!-- 分值 -->
          <el-form-item label="分值" prop="scores">
            <el-input-number
              v-model="params.scores"
              :min="0"
              :max="100"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)"
              >保存</el-button
            >
            <el-button
              @click="submitForms(ruleFormRef)"
              v-show="params.id === 0"
              >保存并继续</el-button
            >
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import {
  reactive,
  toRefs,
  shallowRef,
  onBeforeUnmount,
  watchEffect,
  watch
} from "vue";
import { CircleClose, CirclePlus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IToolbarConfig, createToolbar } from "@wangeditor/editor";
import { postDatabasequestionAdd } from "../../apis/databaselist/databaselist";
// const components = { Editor, Toolbar };
const data: any = reactive({
  checked: [],
  drawer: false,
  params: {
    id:0,
    databaseid: 0,
    type: "单选题",
    tags: "",
    // 内容 HTML
    title: "",
    answer: "",
    scores: null,
    explains: "",
    answers: [
      { answerno: "A", content: "" },
      { answerno: "B", content: "" },
      { answerno: "C", content: "" },
      { answerno: "D", content: "" },
    ],
  },
  ruleFormRef: "",
  formSize: "default",
  rules: {
    title: [
      {
        required: true,
        message: "题干必填",
        trigger: "blur",
      },
    ],
    answers: [
      {
        required: true,
        message: "选择答案必填",
        trigger: "blur",
      },
    ],
    scores: [
      {
        required: true,
        message: "请输入分值",
        trigger: "blur",
      },
    ],
    answer: [
      {
        required: true,
        message: "正确答案必填",
        trigger: "blur",
      },
    ],
  },
  mode: "default",
  blank: [],
});

const { blank, drawer, params, rules, ruleFormRef, formSize, mode, checked } =
  toRefs(data);
// 接受父组件参数
const props = defineProps({
  is: {
    type: Boolean,
  },
  databaseid: {
    type: Number,
  },
  dataUp: {
    type: Object,
  },
});
watch(()=>data.params.title,() => {
  if (data.params.title.match(/\[\]/g) != null) {
    data.blank = data.params.title
      .match(/\[\]/g)
      .map((item: any,index:number) => (item = data.blank[index]));
  } else {
    data.blank = [];
  }
},{immediate:false});
// 子传父
const emits = defineEmits(["isOpen"]);
// 点击x关闭
const handleClose = () => {
  // 数组下标0 弹出是否关闭   1 加载
  emits("isOpen", [false, false]);
};
// 多选框内容改变
const checkboxChange = (e: any) => {
  var checkeds: string = "";
  for (const item in e) {
    checkeds = checkeds + e[item] + "|";
  }
  params.value.answer = checkeds.slice(0, checkeds.length - 1);
};
// 点击删除选项
const answersDel = (index: number) => {
  if (index < params.value.answers.length - 1) {
    for (var i = index; i < params.value.answers.length - 1; i++) {
      params.value.answers[i].content = params.value.answers[i + 1].content;
    }
  }
  params.value.answers.splice(params.value.answers.length - 1, 1);
};
// 点击添加选项
const answersAdd = () => {
  if (data.params.answers.length === 0) {
    data.params.answers.push({ answerno: "A", content: "" });
  } else if (data.params.answers.length === 1) {
    data.params.answers.push({ answerno: "B", content: "" });
  } else if (data.params.answers.length === 2) {
    data.params.answers.push({ answerno: "C", content: "" });
  } else if (data.params.answers.length === 3) {
    data.params.answers.push({ answerno: "D", content: "" });
  } else if (data.params.answers.length === 4) {
    data.params.answers.push({ answerno: "E", content: "" });
  } else if (data.params.answers.length === 5) {
    data.params.answers.push({ answerno: "F", content: "" });
  } else if (data.params.answers.length === 6) {
    data.params.answers.push({ answerno: "G", content: "" });
  } else if (data.params.answers.length === 7) {
    data.params.answers.push({ answerno: "H", content: "" });
  } else if (data.params.answers.length === 8) {
    data.params.answers.push({ answerno: "I", content: "" });
  } else if (data.params.answers.length === 9) {
    data.params.answers.push({ answerno: "G", content: "" });
  } else if (data.params.answers.length === 10) {
    data.params.answers.push({ answerno: "K", content: "" });
  } else if (data.params.answers.length === 11) {
    data.params.answers.push({ answerno: "L", content: "" });
  } else if (data.params.answers.length === 12) {
    data.params.answers.push({ answerno: "M", content: "" });
  } else if (data.params.answers.length === 13) {
    data.params.answers.push({ answerno: "N", content: "" });
  } else if (data.params.answers.length === 14) {
    data.params.answers.push({ answerno: "O", content: "" });
  } else if (data.params.answers.length === 15) {
    data.params.answers.push({ answerno: "P", content: "" });
  } else if (data.params.answers.length === 16) {
    data.params.answers.push({ answerno: "Q", content: "" });
  } else if (data.params.answers.length === 17) {
    data.params.answers.push({ answerno: "R", content: "" });
  } else if (data.params.answers.length === 18) {
    data.params.answers.push({ answerno: "S", content: "" });
  } else if (data.params.answers.length === 19) {
    data.params.answers.push({ answerno: "T", content: "" });
  } else if (data.params.answers.length === 20) {
    data.params.answers.push({ answerno: "U", content: "" });
  } else if (data.params.answers.length === 21) {
    data.params.answers.push({ answerno: "V", content: "" });
  } else if (data.params.answers.length === 22) {
    data.params.answers.push({ answerno: "W", content: "" });
  } else if (data.params.answers.length === 23) {
    data.params.answers.push({ answerno: "X", content: "" });
  } else if (data.params.answers.length === 24) {
    data.params.answers.push({ answerno: "Y", content: "" });
  } else if (data.params.answers.length === 25) {
    data.params.answers.push({ answerno: "Z", content: "" });
  } else {
    ElMessage({
      message: "只能添加这么几个选项！",
      type: "warning",
    });
  }
};
// 回显
if (props.dataUp) {
  const dataUpNew = JSON.parse(JSON.stringify(props.dataUp));
  if (dataUpNew.type === "填空题") {
    data.blank = dataUpNew.answer.split("|");
  }
  if (dataUpNew.type === "多选题") {
    params.value = dataUpNew;
    data.checked = dataUpNew.answer.split("|");
  } else {
    params.value = dataUpNew;
  }
}
data.drawer = props.is;
data.params.databaseid = props.databaseid;
if (data.params.id === 0) {
  data.params.answers.map((item: any) => (item.content = ""));
  data.checked = [];
}
// 请求添加接口
const databasequestionAdd = async (params: any) => {
  // 加载
  emits("isOpen", [true, true]);
  const res: any = await postDatabasequestionAdd(params);
  if (res.errCode === 10000) {
    // 加载完成
    emits("isOpen", [true, false]);
    if (params.id>0) {
      ElMessage({
        message: "修改成功",
        type: "success",
      });
    } else {
      ElMessage({
        message: "添加成功",
        type: "success",
      });
    }
  } else {
    ElMessage.error(res.errMsg);
  }
};
// 点击确定添加
const submitForm = async (formEl: any) => {
  if (params.value.type === "填空题") {
    data.params.answer = data.blank.join("|");
  }
  if (!formEl) return;
  if (params.value.title === "<p><br></p>") {
    ElMessage("题干必填！");
    return;
  }
  if (params.value.type === "单选题" || params.value.type === "多选题") {
    for (const item in params.value.answers) {
      if (params.value.answers[item].content === "") {
        ElMessage("请填写所有选项！");
        return;
      }
    }
  }
  for (const item in data.blank) {
    if (!data.blank[item]) {
      ElMessage("正确答案必填！");
      return;
    }
  }
  if (!data.params.answer) {
    ElMessage("正确答案必填！");
    return;
  }
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      databasequestionAdd(params.value);
      formEl.resetFields();
      emits("isOpen", [false, false]);
      data.drawer = false;
    } else {
      return;
    }
  });
};
// 点击保存并继续添加
const submitForms = async (formEl: any) => {
  if (!formEl) return;
  if (params.value.type === "单选题" || params.value.type === "多选题") {
    for (const item in params.value.answers) {
      if (params.value.answers[item].content === "") {
        ElMessage("请填写所有选项！");
        return;
      }
    }
  }
  if (params.value.type === "填空题") {
    data.params.answer = data.blank.join("|");
  }
  if (params.value.title === "<p><br></p>") {
    ElMessage("题干必填！");
    return;
  }
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      databasequestionAdd(params.value);
      formEl.resetFields();
      data.params.answers.map((item: any) => (item.content = ""));
      data.params = {
      databaseid: 0,
      type: "单选题",
      tags: "",
      // 内容 HTML
      title: "",
      answer: "",
      scores: null,
      explains: "",
      answers: [
        {
          answerno: "A",
          content: "",
        },
        {
          answerno: "B",
          content: "",
        },
        {
          answerno: "C",
          content: "",
        },
        {
          answerno: "D",
          content: "",
        },
      ],
    };
    } else {
      return;
    }
  });
};
// 点击取消
const resetForm = (formEl: any) => {
  if (!formEl) return;
  formEl.resetFields();
  emits("isOpen", [false, false]);
};
// 题的类型内容改变
const radioChange = () => {
  (data.params.answer = ""), (data.params.explains = "");
};
// 富文本----------------------------------------------------------
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
const toolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    // 菜单 key
    "bold",
    "italic",
    "underline",
    "through",
    "color",
    "bgColor",
    "bulletedList",
    "numberedList",
    "justifyLeft",
    "justifyCenter",
    "justifyRight",
    "insertTable",
    // 继续配置其他菜单...
    {
      key: "group-image", // 必填，要以 group 开头
      title: "图片", // 必填
      menuKeys: ["uploadImage", "insertImage"],
    },
  ],
};

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const editorConfig: any = { MENU_CONF: {} };
editorConfig.MENU_CONF["uploadImage"] = {
  server: "http://www.eshareedu.cn/exam/api/upload/editeradd", // 上传图片地址
  timeout: 5 * 1000, // 5s

  fieldName: "file",
  meta: { baseUrl: "" },
  metaWithUrl: true, // 参数拼接到 url 上
  headers: { Authorization: sessionStorage.getItem("token") },

  maxFileSize: 10 * 1024 * 1024, // 10M

  base64LimitSize: 5 * 1024, // 5kb 以下插入 base64

  onBeforeUpload(files: any) {
    console.log("onBeforeUpload", files);

    return files; // 返回哪些文件可以上传
    // return false 会阻止上传
  },
  onProgress(progress: any) {
    console.log("onProgress", progress);
  },
  onSuccess(file: any, res: any) {
    console.log("onSuccess", file, res);
  },
  onFailed(file: any, res: any) {
    alert(res.message);
    console.log("onFailed", file, res);
  },
  onError(file: any, err: any, res: any) {
    alert(err.message);
    console.error("onError", file, err, res);
  },

  // 用户自定义插入图片
  customInsert(res: any, insertFn: any) {
    // 自己插入图片
    insertFn("http://www.eshareedu.cn/exam/upload/" + res.data[0].url.slice(1));
  },
};
// 富文本---------------end
</script>

<style lang="less" scoped>
</style>
